<template>
  <div id="wrap">
    <!-- 歌曲信息 -->
    <div class="songInfo">
      <h3 class="name">{{ currentSong.name }}</h3>
      <div class="singer">{{ currentSong.ar[0].name }}</div>
      <!-- <div class="album">依然范特西</div> -->
    </div>
    <!-- 歌曲图片 -->
    <div class="songImg">
      <img ref="songImg" :src="currentSong.al.picUrl" alt="" />
    </div>

    <!-- 进度条 -->
    <progress-comp
      ref="progress"
      :indexObj="indexObj"
      :musicInfoList="musicInfoList"
      @setImgPlay="setImgPlay"
    />

    <!-- 底部菜单 -->
    <ul class="control">
      <li :class="{ liking: isLike }" @touchend="isLike = !isLike"></li>
      <li @touchend="switchLast"></li>
      <li :class="{ playing: isPlaying }" @touchend="playCurSong"></li>
      <li @touchend="switchNext"></li>
      <li @touchend="closeListControl(true)"></li>
    </ul>

    <!-- 弹出列表 -->
    <list-control
      ref="musicList"
      :show="showListControl"
      @closeListControl="closeListControl"
      @loadMusic="loadMusic"
    />
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import ListControl from "./listControl.vue";
import ProgressComp from "./progressComp.vue";
export default {
  async created() {
    await this.getSongUrl();
    this.indexObj = new this.$player.controlIndex(this.musicList.length); //给索引值对象赋值
    // this.storageSongId(id);	//索引值对象身上的当前索引值要更新
    await this.loadMusic(this.indexObj.index); //加载音乐
  },
  components: {
    ProgressComp,
    ListControl,
  },
  data() {
    return {
      record: null, // 唱片的dom的值
      indexObj: {
        index: 0,
        len: 1,
      }, //索引值对象（用于切歌）
      rotateTimer: null, //旋转唱片的定时器
      curIndex: 0, //当前播放歌曲的索引值
      list: null, //列表切歌对象（在listPlay里赋了值）
      move: false,
      isLike: false,
      isPlaying: false,
      showListControl: false,
      rotateTimer: null, //旋转唱片的定时器
      currentSong: {
        id: 1836108253,
        url: "http://m701.music.126.net/20210903060527/9c1ff85c4b0b1b2b3e914ead36be1cdc/jdymusic/obj/wo3DlMOGwrbDjj7DisKw/8338087914/3c11/3634/2e84/63ee4073973cab97d74829df4c3cbd98.mp3",
        br: 128001,
        size: 5825559,
        md5: "63ee4073973cab97d74829df4c3cbd98",
        code: 200,
        expi: 1200,
        type: "mp3",
        gain: 0,
        fee: 8,
        uf: null,
        payed: 0,
        flag: 0,
        canExtend: false,
        freeTrialInfo: null,
        level: null,
        encodeType: null,
        freeTrialPrivilege: {
          resConsumable: false,
          userConsumable: false,
        },
        freeTimeTrialPrivilege: {
          resConsumable: false,
          userConsumable: false,
          type: 0,
          remainTime: 0,
        },
        urlSource: 0,
        name: "海阔天空",
        id: 347230,
        pst: 0,
        t: 0,
        ar: [
          {
            id: 11127,
            name: "Beyond",
            tns: [],
            alias: [],
          },
        ],
        alia: [],
        pop: 100,
        st: 0,
        rt: "600902000004240302",
        fee: 1,
        v: 106,
        crbt: null,
        cf: "",
        al: {
          id: 34209,
          name: "海阔天空",
          picUrl:
            "https://p1.music.126.net/8y8KJC1eCSO_vUKf2MyZwA==/109951165796899183.jpg",
          tns: [],
          pic_str: "109951165796899183",
          pic: 109951165796899180,
        },
        dt: 326000,
        h: {
          br: 320000,
          fid: 0,
          size: 13042459,
          vd: 0,
        },
        m: {
          br: 192000,
          fid: 0,
          size: 7825492,
          vd: 2310,
        },
        l: {
          br: 128000,
          fid: 0,
          size: 5217009,
          vd: 1324,
        },
        a: null,
        cd: "1",
        no: 1,
        rtUrl: null,
        ftype: 0,
        rtUrls: [],
        djId: 0,
        copyright: 1,
        s_id: 0,
        mark: 8192,
        originCoverType: 0,
        originSongSimpleData: null,
        tagPicList: null,
        resourceState: true,
        version: 106,
        songJumpInfo: null,
        single: 0,
        noCopyrightRcmd: null,
        mv: 376199,
        rtype: 0,
        rurl: null,
        mst: 9,
        cp: 7002,
        publishTime: 746812800000,
        tns: ["Boundless Oceans, Vast Skies"],
        // name: "海阔天空(抖音版)",
        // artists: [
        //   {
        //     id: 31842776,
        //     name: "哪吒三太子",
        //     picUrl: null,
        //     alias: [],
        //     albumSize: 0,
        //     picId: 0,
        //     img1v1Url:
        //       "https://p1.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg",
        //     img1v1: 0,
        //     trans: null,
        //   },
        // ],
        // album: {
        //   id: 125812089,
        //   name: "一点点心动",
        //   artist: {
        //     id: 0,
        //     name: "",
        //     picUrl: null,
        //     alias: [],
        //     albumSize: 0,
        //     picId: 0,
        //     img1v1Url:
        //       "https://p1.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg",
        //     img1v1: 0,
        //     trans: null,
        //   },
        //   publishTime: 1546272000000,
        //   size: 0,
        //   copyrightId: 1416503,
        //   status: 1,
        //   picId: 109951165876318580,
        //   mark: 0,
        // },
        // duration: 364094,
        // copyrightId: 1416503,
        // status: 0,
        // alias: [],
        // rtype: 0,
        // ftype: 0,
        // mvid: 0,
        // rUrl: null,
        // mark: 0,
      }, // 当前音乐
      songInfoList: [
        {
          id: 1868874994,
          url: "http://m801.music.126.net/20210821213801/21ae57b0fe31353720a9611435fc5ea0/jdymusic/obj/wo3DlMOGwrbDjj7DisKw/10295849120/905a/d5bf/20ca/ab6a6615fe18156657f36843cfd57182.mp3",
          br: 128002,
          size: 3826460,
          md5: "ab6a6615fe18156657f36843cfd57182",
          code: 200,
          expi: 1200,
          type: "mp3",
          gain: 0,
          fee: 8,
          uf: null,
          payed: 0,
          flag: 64,
          canExtend: false,
          freeTrialInfo: null,
          level: null,
          encodeType: null,
          freeTrialPrivilege: {
            resConsumable: false,
            userConsumable: false,
          },
          freeTimeTrialPrivilege: {
            resConsumable: false,
            userConsumable: false,
            type: 0,
            remainTime: 0,
          },
          urlSource: 0,
        },
      ],
      musicInfoList: [],
    };
  },
  computed: {
    ...mapState({
      songId: (state) => state.songId,
      songIds: (state) => state.songIds,
      musicList: (state) => state.musicList,
    }),
  },
  watch: {
    currentSong: function (newVal, oldVal) {
      if (newVal && newVal.al) {
        this.$player.blurImg(newVal.al.picUrl); //给body添加背景图片
      }
    },
  },
  beforeDestroy() {
    clearInterval(this.rotateTimer);
  },
  methods: {
    async getSongUrl() {
      const { data } = await this.$api.getSongUrl(this.songIds.join(","));
      if (data.code === 200) {
        this.songInfoList = data.data;
        this.musicInfoList = this.musicList.map((item, index) => {
          return Object.assign(
            item,
            this.songInfoList.filter((ele) => ele.id === item.id)[0]
          );
        });
      } else {
        Toast.fail(`code: ${data.code}`);
      }
    },
    closeListControl(flag) {
      if (flag) {
        this.$refs.musicList.slideUp();
      }
      this.showListControl = flag;
    },
    loadMusic(index) {
      const self = this;

      this.currentSong = this.musicInfoList[index];
      this.$player.music.load(this.currentSong.url); //加载点击对应的索引值的那首歌曲
      this.$refs.progress.renderAllTime(this.currentSong.dt); //加载歌曲的总时间
      //播放音乐（只有音乐的状态为play的时候才能播放）
      if (this.$player.music.status === "play") {
        this.$player.music.play();
        this.isPlaying = true; //按钮状态变成播放状态
        this.imgRotate(0); //旋转图片
        this.$refs.progress.move(0); //切歌的时候需要让进度条跟着走
      }
      //改变列表里歌曲的选中状态
      this.$refs.musicList.changeSelect(index);
      this.curIndex = index; //存储当前歌曲对应的索引值

      //歌曲播放到头了要切歌
      this.$player.music.end(function () {
        self.loadMusic(this.indexObj.next());
      });
    },
    imgRotate(deg) {
      const self = this;
      //旋转唱片
      this.record = document.querySelector(".songImg img"); //旋转图片
      clearInterval(this.rotateTimer);

      this.rotateTimer = setInterval(function () {
        deg = +deg + 0.2; //前面的加号是把字符串转数字
        self.$refs.songImg.style.transform = "rotate(" + deg + "deg)";
        self.$refs.songImg.dataset.rotate = deg; //把旋转的角度存到标签身上，为了暂停后继续播放能取到
        // self.record.style.transform = 'rotate(' + deg + 'deg)';
        // self.record.dataset.rotate = deg;	//把旋转的角度存到标签身上，为了暂停后继续播放能取到
      }, 1000 / 60);
    },
    switchLast() {
      //上一首
      this.$player.music.status = "play";
      this.loadMusic(this.indexObj.prev());
    },
    switchNext() {
      //下一首
      this.$player.music.status = "play";
      this.loadMusic(this.indexObj.next());
    },
    playCurSong() {
      //播放、暂停
      if (this.$player.music.status == "play") {
        //歌曲的状态为播放，点击后要暂停
        this.$player.music.pause(); //歌曲暂停
        this.isPlaying = false; //按钮变成暂停状态
        this.imgStop(); //停止旋转图片

        this.$refs.progress.stop(); //让进度条停止
      } else {
        //歌曲的状态为暂停，点击后要播放
        this.$player.music.play(); //歌曲播放
        this.isPlaying = true; //按钮变成播放状态

        //第二次播放的时候需要加上上一次旋转的角度。但是第一次的时候这个角度是没有的，取不到。所以做了一个容错处理
        let deg = this.$refs.songImg.dataset.rotate || 0;
        this.imgRotate(deg); //旋转图片

        this.$refs.progress.move(); //让进度条走
      }
    },
    imgStop() {
      //停止图片旋转
      clearInterval(this.rotateTimer);
    },
    setImgPlay() {
      let deg = this.$refs.songImg.dataset.rotate || 0;
      this.imgRotate(deg); //旋转图片
      this.isPlaying = true; //按钮状态变成播放状态
    },
  },
};
</script>

<style lang="less" scoped>
</style>
